package zpe.controledeacesso.util;

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import zpe.controledeacesso.model.bean.Email;
import zpe.genericcrud.exception.ApplicationException;

import com.sun.mail.util.MailSSLSocketFactory;


public class EmailUtil {
	
	private JavaMailSenderImpl mailSender;
	
	/* 
	  
	    <prop key="mail.smtps.auth">true</prop>
	    <prop key="mail.smtps.userset">true</prop>
	    
	    <prop key="mail.smtp.auth">true</prop>
		<prop key="mail.smtp.ssl.enable">true</prop>
		<prop key="mail.smtp.ssl.trust">*</prop>
		<prop key="mail.smtp.port">465</prop>
		<prop key="mail.smtp.starttls.enable">true</prop>
	    <prop key="mail.smtp.requiresAuthentication">true</prop>
		<prop key="mail.smtp.socketFactory.port">465</prop>
		<prop key="mail.smtp.socketFactory.fallback">false</prop>
		<!-- <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> -->
	    <prop key="mail.smtp.debug">true</prop>
	  
	 */
	public EmailUtil() {
		// TODO Auto-generated constructor stub
		
		mailSender = new JavaMailSenderImpl();
		
		mailSender.setUsername("sistemarh@seduc.ce.gov.br");
		mailSender.setPassword("sistemarh");
		mailSender.setHost("smtp.seduc.ce.gov.br");
		
		Properties properties = new Properties();
		
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.userset", "true");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.trust", "*");
		properties.put("mail.smtp.port", "465");
		properties.put("mail.mime.charset", "UTF-8");
		
		properties.put("mail.smtp.requiresAuthentication", "true");
		properties.put("mail.transport.protocol", "smtps");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.socketFactory.fallback", "false");
		properties.put("mail.smtp.socketFactory.port", "465");
		
		properties.put("mail.debug", "false"); 
		
		mailSender.setJavaMailProperties( properties );
		
	}
	
	/*public static boolean enviaEmail( Email email ) {
		try {

			Properties p = new Properties();
			p.setProperty("mail.transport.protocol", "smtp");
			p.put("mail.host", email.getServidor());
			p.put("mail.smtp.auth", "true");

			Session session = Session.getDefaultInstance(p, new Autenticador(
					email.getUsuario().toLowerCase(), email.getSenha() ));

			Transport transport = session.getTransport();

			MimeMessage message = new MimeMessage(session);
			message.setSubject( email.getAssunto() );
			message.setFrom(new InternetAddress( email.getRemetente() ));

			MimeMultipart multipart = new MimeMultipart("related");	

			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setContent( email.getMensagem(), "text/html");
			multipart.addBodyPart(messageBodyPart);
			message.setContent(multipart);
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					email.getDestino().toLowerCase()));
			transport.connect();

			MailcapCommandMap mc = (MailcapCommandMap)CommandMap.getDefaultCommandMap();
			mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
			mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
			mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
			mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
			mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
			CommandMap.setDefaultCommandMap(mc);

			transport.sendMessage(message, message
					.getRecipients(Message.RecipientType.TO));
			transport.close();

		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}*/

	public static String geraSenha() {

		String[] carct = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
				"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
				"Y", "Z" };

		String senha = "";

		for (int x = 0; x < 6; x++) {
			int j = (int) (Math.random() * carct.length);
			senha += carct[j];
		}

		return senha;
	}
	
	public void enviarEmail(Email email) {
		enviarEmail(email, null);
	}
	
	public void enviarEmail(Email email, Map<String, String> arquivos) {
		
		try {
			
			MimeMessage mimiMessage = mailSender.createMimeMessage();
			
			MimeMessageHelper mimeMessageHelper;
			mimeMessageHelper = new MimeMessageHelper(mimiMessage, true);
		
			mimeMessageHelper.setTo(email.getDestino());
			mimeMessageHelper.setText(email.getMensagem(), true);
			mimeMessageHelper.setSubject(email.getAssunto());
			mimeMessageHelper.setFrom(email.getUsuario());
	
			if (arquivos != null) {
				FileSystemResource file = null;
				for (Map.Entry<String, String> item : arquivos.entrySet()) {
					file = new FileSystemResource(new File(item.getValue()));
					mimeMessageHelper.addAttachment(item.getKey(), file);
				}
			}
			
			MailcapCommandMap mc = (MailcapCommandMap)CommandMap.getDefaultCommandMap();
			mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
			mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
			mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
			mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
			mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
			CommandMap.setDefaultCommandMap(mc);
			
			mailSender.setProtocol("smtps");
			
			MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
	    	socketFactory.setTrustAllHosts(true);
	    	
	    	mailSender.getSession().getProperties().put("mail.smtps.socketFactory", socketFactory);
			
			mailSender.send(mimiMessage);
		
		} catch (MessagingException e) {
			throw new ApplicationException(
					"Ocorreu um problema no envio de e-mail. Tente novamente mais tarde.");
		} catch (GeneralSecurityException e) {
			throw new ApplicationException(
					"Ocorreu um problema no envio de e-mail. Tente novamente mais tarde.");
		} 
	}
}
